package cn.zooz.admin.config.web;

import cn.zooz.common.util.inteceptor.CommonInterceptor;
import cn.zooz.common.util.inteceptor.LogMDCInterceptor;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.resource.VersionResourceResolver;

import javax.annotation.Resource;
import java.util.Locale;

/**
 * Created by Bradish7Y on 2017/8/23.
 */
@Configuration
//@EnableWebMvc 不要使用此注解，否则会覆盖自动配置
public class WebMVCConfig extends WebMvcConfigurerAdapter {

    /**
     * 静态文件交由默认servlet执行
     *
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public CommonInterceptor commonInterceptor() {
        return new CommonInterceptor();
    }

    @Bean
    public LogMDCInterceptor logMDCInterceptor() {
        return new LogMDCInterceptor();
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
        localeChangeInterceptor.setParamName("lang");

        return localeChangeInterceptor;
    }

    @Bean
    public LocaleResolver localeResolver() {
        CookieLocaleResolver locale = new CookieLocaleResolver();
        locale.setDefaultLocale(Locale.US);

//        SessionLocaleResolver locale = new SessionLocaleResolver();
//        locale.setDefaultLocale(Locale.US);
        return locale;
    }

    /**
     * 拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(commonInterceptor());//通用拦截器
        registry.addInterceptor(logMDCInterceptor());//为日志加上session
        registry.addInterceptor(localeChangeInterceptor());//本地化（语言）
    }

    /**
     * CORS跨域
     */
//    @Bean
//    public WebMvcConfigurer corsConfigurer() {
//        return new WebMvcConfigurerAdapter() {
//            @Override
//            public void addCorsMappings(CorsRegistry registry) {
//                registry.addMapping("/api/**").allowedOrigins("*")
//                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
//                .allowCredentials(false).maxAge(3600);
//            }
//        };
//    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        super.addCorsMappings(registry);
//        registry.addMapping("/api/**").allowedOrigins("*")
//                .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
//                .allowCredentials(false).maxAge(3600);
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //cacheControl
//        registry.addResourceHandler("/theme/**").addResourceLocations("/static/theme/")
//                .setCachePeriod(86400 * 7).setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
//
//        //为js增加版本号
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/")
                .setCachePeriod(86400 * 7).resourceChain(false).addResolver(
                new VersionResourceResolver().addContentVersionStrategy("/**"));

        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/").setCachePeriod(86400 * 7);

        registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/img/")
                .setCachePeriod(86400 * 7);
    }

    /**
     * validated验证，错误提示(id.size.not.valid=id长度在 {min} 和 {max} 之间）
     */
    @Bean
    public Validator mvcValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setProviderClass(HibernateValidator.class);
        validator.setValidationMessageSource(messageSource);

        return validator;
    }

    @Override
    public Validator getValidator() {
        return mvcValidator();
    }

    @Resource
    private MessageSource messageSource;
}
